﻿using Model.DocumentDB;
using Studio.DocumentDB.Dialogs;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace Studio.DocumentDB
{
    /// <summary>Tool bar control of the Studio.</summary>
    public partial class ToolBarUserControl : UserControl
    {
        /// <summary>Constructor.</summary>
        public ToolBarUserControl()
        {
            InitializeComponent();
        }

        //  Connect to a new DocumentDB Account
        private void Connect_Click(object sender, RoutedEventArgs e)
        {
            var studio = DataContext as StudioViewModel;

            if (studio != null)
            {
                var dialog = new AccountCredentialsWindow
                {
                    WindowStartupLocation = WindowStartupLocation.CenterOwner,
                    Owner = Window.GetWindow(this),
                    Studio = studio
                };

                if (dialog.ShowDialog() == true)
                {
                    TelemetryAgent.Instance.UseFeature(Features.ConnectAccount);
                }
            }
        }

        private void Disconnect_Click(object sender, RoutedEventArgs e)
        {
            var studio = DataContext as StudioViewModel;

            if (studio != null)
            {
                var account = studio.Accounts.SelectedValue as AccountViewModel;
                var answer = MessageBox.Show(
                    Window.GetWindow(this),
                    "Are you sure you want to disconnect from " + account.Id + "?",
                    "Disconnect account",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Question);

                if (answer == MessageBoxResult.Yes)
                {
                    studio.Accounts.Remove(account);

                    var waitWindow = new WaitWindow
                    {
                        WaitingTask = studio.Accounts.SaveAsync(),
                        Owner = Window.GetWindow(this)
                    };

                    waitWindow.ShowDialog();

                    waitWindow.WaitingTask.Wait();
                    TelemetryAgent.Instance.UseFeature(Features.DisconnectAccount);
                }
            }
        }

        private async void Refresh_Click(object sender, RoutedEventArgs e)
        {
            var studio = DataContext as StudioViewModel;

            if (studio != null)
            {
                var refreshable = studio.Accounts.SelectedValue as IRefreshable;

                if (refreshable != null)
                {
                    await ErrorHelper.HandleAsync(() => refreshable.RefreshAsync(), this, "Refresh:  {0}");
                }
            }
        }

        private void NewDB_Click(object sender, RoutedEventArgs e)
        {
            var studio = DataContext as StudioViewModel;

            if (studio != null)
            {
                var dbFolder = studio.Accounts.SelectedValue;
                //  Find account owning the db folder
                var account = (from a in studio.Accounts
                               where object.ReferenceEquals(dbFolder, a.DatabaseFolder)
                               select a).First();
                var dialog = new NewDbWindow
                {
                    Account = account,
                    WindowStartupLocation = WindowStartupLocation.CenterOwner,
                    Owner = Window.GetWindow(this)
                };

                if (dialog.ShowDialog() == true)
                {
                    TelemetryAgent.Instance.UseFeature(Features.AddDatabase);
                }
            }
        }

        private async void RemoveDB_Click(object sender, RoutedEventArgs e)
        {
            var studio = DataContext as StudioViewModel;

            if (studio != null)
            {
                var db = studio.Accounts.SelectedValue as DatabaseViewModel;
                //  Find account owning the db
                var account = (from a in studio.Accounts
                               from d in a.DatabaseFolder.FolderContent
                               where object.ReferenceEquals(db, d)
                               select a).First();
                var answer = MessageBox.Show(
                    Window.GetWindow(this),
                    "How you sure you want to destroy database '" + db.Name + "'?",
                    "Confirmation",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Question);

                if (answer == MessageBoxResult.Yes)
                {
                    await ErrorHelper.HandleAsync(
                        async () =>
                        {
                            var waitWindow = new WaitWindow
                            {
                                WaitingTask = account.DeleteDatabaseAsync(db),
                                Owner = Window.GetWindow(this)
                            };

                            waitWindow.ShowDialog();

                            await waitWindow.WaitingTask;

                            TelemetryAgent.Instance.UseFeature(Features.RemoveDatabase);
                        }, this, "Delete DB:  {0}");
                }
            }
        }

        private void NewCollection_Click(object sender, RoutedEventArgs e)
        {
            var studio = DataContext as StudioViewModel;

            if (studio != null)
            {
                var collectionFolder = studio.Accounts.SelectedValue;
                //  Find db owning the collection folder
                var db = (from a in studio.Accounts
                          from d in a.DatabaseFolder.FolderContent
                          where object.ReferenceEquals(collectionFolder, d.CollectionFolder)
                          select d).First();
                var dialog = new NewCollectionWindow
                {
                    Database = db,
                    WindowStartupLocation = WindowStartupLocation.CenterOwner,
                    Owner = Window.GetWindow(this)
                };

                if (dialog.ShowDialog() == true)
                {
                    TelemetryAgent.Instance.UseFeature(Features.AddCollection);
                }
            }
        }

        private async void RemoveCollection_Click(object sender, RoutedEventArgs e)
        {
            var studio = DataContext as StudioViewModel;

            if (studio != null)
            {
                var collection = studio.Accounts.SelectedValue as CollectionViewModel;
                //  Find db owning the collection
                var db = (from a in studio.Accounts
                          from d in a.DatabaseFolder.FolderContent
                          from c in d.CollectionFolder.FolderContent
                          where object.ReferenceEquals(collection, c)
                          select d).First();
                var answer = MessageBox.Show(
                    Window.GetWindow(this),
                    "How you sure you want to destroy collection '" + collection.Name + "'?",
                    "Confirmation",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Question);

                if (answer == MessageBoxResult.Yes)
                {
                    await ErrorHelper.HandleAsync(
                        async () =>
                        {
                            var waitWindow = new WaitWindow
                            {
                                WaitingTask = db.DeleteCollectionAsync(collection),
                                Owner = Window.GetWindow(this)
                            };

                            waitWindow.ShowDialog();

                            await waitWindow.WaitingTask;

                            TelemetryAgent.Instance.UseFeature(Features.RemoveCollection);
                        }, this, "Delete collection:  {0}");
                }
            }
        }

        private void NewDocument_Click(object sender, RoutedEventArgs e)
        {
            var studio = DataContext as StudioViewModel;

            if (studio != null)
            {
                var documentFolder = studio.Accounts.SelectedValue as FolderViewModel<DocumentViewModel, CollectionViewModel>;
                var collection = documentFolder.Parent;

                var dialog = new NewDocumentWindow
                {
                    Collection = collection,
                    WindowStartupLocation = WindowStartupLocation.CenterOwner,
                    Owner = Window.GetWindow(this)
                };

                if (dialog.ShowDialog() == true)
                {
                    TelemetryAgent.Instance.UseFeature(Features.AddDocument);
                }
            }
        }

        private async void DeleteDocument_Click(object sender, RoutedEventArgs e)
        {
            var studio = DataContext as StudioViewModel;

            if (studio != null)
            {
                var document = studio.Accounts.SelectedValue as DocumentViewModel;
                var answer = MessageBox.Show(
                    Window.GetWindow(this),
                    "Are you sure you want to remove document " + document.Name + "?",
                    "Remove Document",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Question);

                if (answer == MessageBoxResult.Yes)
                {
                    await ErrorHelper.HandleAsync(
                        async () =>
                        {
                            var waitWindow = new WaitWindow
                                {
                                    WaitingTask = document.DeleteAsync(),
                                    Owner = Window.GetWindow(this)
                                };

                            waitWindow.ShowDialog();

                            await waitWindow.WaitingTask;

                            TelemetryAgent.Instance.UseFeature(Features.RemoveDocument);
                        }, this, "Delete document:  {0}");
                }
            }
        }
    }
}